# coding:utf-8

#封装notion的操作api

import datetime

import json
import re

from const import *
import requests

def count_week(date):
    """根据date 计算这是第几年第几周"""
    year,week,w = date.isocalendar()
    return f"{year}年第{week}周"

def count_month(date:datetime.date):
    """根据date 计算这是第几年第几周"""
    year=date.year
    month = date.month
    return f"{year%2000}年{month}月"

def creat_week(week_index):
    """
    创建新的一周 创建第week_index 周
    """
    url = ""



class MyNotion():
    secret_key = ""
    days_database_id = ""
    weeks_database_id = ""
    bill_database_id = ""
    month_database_id = ""
    def __init__(self):
        self.session=requests.session()
        headers= {
        "Authorization":  self.secret_key,
        "Notion-Version": "2022-06-28"
        }
        self.session.headers=headers

    #针对习惯管理的一些方法
    #创建每天的记录  如果我忘记记录了  则创建一个都为空的
    def add_day_log(self,day_name=None,learn_en=False):

        """日期 是否学习了新技能  是否背单词"""

        if day_name is None:
            #如果日期为None 则以今天的日期为名字
            _date = datetime.date.today()
            day_name=str(_date)
            current_weeks=count_week(_date)
        else:
            _date=datetime.datetime.strptime(day_name,"%Y-%m-%d")
            day_name=str(_date)

            current_weeks=count_week(_date)
        # print(_date)
        week_relation_id = self.query_current_weeks(current_weeks)
        # print(week_relation_id)
        properties = {'名称': {'id': 'title',
                                'title': [{'plain_text': day_name,
                                           'text': {'content': day_name, 'link': None},
                                           'type': 'text'}],
                                'type': 'title'},
     '学习一个新技能': {'checkbox': False, 'id': 'APno', 'type': 'checkbox'},
     '日期': {'date': {'end': None, 'start': day_name, 'time_zone': None},
            'id': 'Jk%3D%40',
            'type': 'date'},
     '每周汇总': {'has_more': False,
              'id': 'O%60Zo',
              'relation': [{'id': week_relation_id}],
              'type': 'relation'},
     '背单词': {'checkbox': learn_en, 'id': 'Tq%3BW', 'type': 'checkbox'},
     '文献管理': {'has_more': False, 'relation': [], 'type': 'relation'}}
        result =self.save_to_database(self.days_database_id,properties)
        return result["id"]
    def query_day_info(self,day_name):
        """
        根据名称查询下数据库   拿来查询数据库的结构用
        """
    def query_current_weeks(self,week_name):

        """查询是否存在当前周数
            如果存在周数就返回id
            如果不存在就创建一个并返回id
        """
        query = {"filter": {"property": "周数", "rich_text": {"contains": week_name}}}
        week_info = self.query_database(self.weeks_database_id,query)
        # print(week_relation_id)
        if len(week_info["results"])==0:
            #没有周数  则进行创建一个
            props={"周数":{"id":"title","type":"title",
                   "title": [{"type":"text","text":{"content":week_name,"link":None},

                  "plain_text":week_name,"href":None}]}}
            result  = self.save_to_database(self.weeks_database_id,props)
            return result["id"]
            # print(result)
        else:
            return week_info["results"][0]["id"]


    #记账方面的函数

    def add_bill(self, name=None,money=0,_type="",day_name=None):

        """日期 是否学习了新技能  是否背单词"""

        if day_name is None:
            # 如果日期为None 则以今天的日期为名字
            _date = datetime.date.today()
            day_name = str(_date)
            current_month = count_month(_date)
        else:
            _date = datetime.datetime.strptime(day_name, "%Y-%m-%d")
            day_name = str(_date)

            current_month = count_month(_date)
        # print(_date)
        month_relation_id = self.query_current_month(current_month)
        # print(week_relation_id)
        properties = {'名称': {'id': 'title',
                             'title': [{'plain_text': name,
                                        'text': {'content': name, 'link': None},
                                        'type': 'text'}],
                             'type': 'title'},
                      '类型': {'select': {
                                        # "id":";Dqw",
                                        "name":_type,
                                        # "color":"pink"
                                    },
                        'type': 'select'},
                      '日期': {'date': {'end': None, 'start': day_name, 'time_zone': None},
                             'id': 'plad',
                             'type': 'date'},
                      '小金库': {'has_more': False,

                               'relation': [{'id': month_relation_id}],
                               'type': 'relation'},
                      '金额': {'number': money, 'type': 'number'},
                      # '读文献记录': {'has_more': False, 'id': 'AlMP', 'relation': [], 'type': 'relation'}

                      }
        result = self.save_to_database(self.bill_database_id, properties)
        return result

    def query_by_date(self,start,end,data_base_id,start_cursor=None):
        """
        根据名称查询下数据库   拿来查询数据库的结构用
        """
        query={

    "filter": {
              "and": [
                {
                                "property":"日期",
                                "date":{
                                "on_or_before":end}
                            },{
                                "property":"日期",
                      "date": {
                                "on_or_after":start}
                            }

              ]
            },

        }
        if start_cursor:
            query["start_cursor"]=start_cursor
        data = self.query_database(data_base_id,query)
        # print(data)
        return data
    def count(self,start,end):

        bill_info = {
            "支出": 0,
            "收入": 0,
            "理财":0,
            "借贷": 0
        }
        day_info={
            "记单词":0,
            "阅读文献":0,
            "学会的技能":0
        }
        start_cursor=None
        while True:
            result = self.query_by_date(start, end, self.bill_database_id,start_cursor=start_cursor)
            bills=result["results"]
            for bill in bills:
                # print(bill)
                properties = bill["properties"]
                if properties["类型"]["select"]["name"]=="理财":
                    bill_info["理财"] += properties["金额"]["number"]

                else:

                    bill_info["支出"] += properties["支出汇总"]["formula"]["number"]
                    bill_info["收入"] += properties["收入汇总"]["formula"]["number"]
                    bill_info["借贷"] += properties["借贷汇总"]["formula"]["number"]
            if result["has_more"]:
                start_cursor=result["next_cursor"]
            else:
                start_cursor=None
                break

        while True:

            result = self.query_by_date(start,end,self.days_database_id,start_cursor=start_cursor)
            days=result["results"]

            for day in days:
                properties=day["properties"]
                # print(properties)
                if properties["学习一个新技能"]["checkbox"]:
                    day_info["学会的技能"]+=1

                if properties["背单词"]["checkbox"]:
                    day_info["记单词"]+=1
                # if properties["学习一个新技能"]["checkbox"]:
                day_info["阅读文献"]+=len(properties["文献管理"]["relation"])

            if result["has_more"]:
                start_cursor=result["next_cursor"]
            else:
                start_cursor=None
                break
        #开始拼接下模板

        model="""支出 {} 元\n收入 {} 元\n理财 {} 元\n借贷 {} 元\n---------\n记单词天数：{}\n阅读文献数量：{}\n学会的技能数量：{}""".format(
            round(bill_info["支出"],2),round(bill_info["收入"],2),round(bill_info["理财"],2),round(bill_info["借贷"],2),
            day_info["记单词"], day_info["阅读文献"], day_info["学会的技能"],

        )
        return model

    def query_current_month(self, current_month):

        """查询是否存在当前周数
            如果存在周数就返回id
            如果不存在就创建一个并返回id
        """
        query = {"filter": {"property": "总账月份", "rich_text": {"contains": current_month}}}
        month_info = self.query_database(self.month_database_id, query)
        # print(week_relation_id)
        if len(month_info["results"]) == 0:
            # 没有周数  则进行创建一个
            props = {"总账月份": {"id": "title", "type": "title",
                            "title": [{"type": "text", "text": {"content": current_month, "link": None},

                                       "plain_text": current_month, "href": None}]}}
            result = self.save_to_database(self.month_database_id, props)
            return result["id"]
            # print(result)
        else:
            return month_info["results"][0]["id"]

    def query_database(self,database_id,query):
        #获取用get

        url=f"https://api.notion.com/v1/databases/{database_id}/query"
        resp = self.session.post(url,json=query)
        # print(resp.text)
        resp=json.loads(resp.text)
        return resp
    def save_to_database(self,database_id,properties):
        #提交数据用post
        body = {
                # 父级信息（即你要创建的页面的上一级页面）
                "parent": {
                    # 父级页面类型，如果我们想在服药记录的数据库中增加一条记录，那么新纪录是什么类型呢？
                    # 答对了！是页面类型，我们创建的是记录，它展开后是一条页面，所以输入 page_id
                    "type": "database_id",
                    # 注意，下面的 "page_id" 项仍需要根据你的创建项目类型变化
                            # 所需要提供的 ID 就是父级页面的 ID，需要手动在链接中进行复制
                            "database_id": database_id
                    },
                # 属性项，在这里决定新记录的属性是什么，这里我用服药记录举例
                "properties":properties
                }
        url="https://api.notion.com/v1/pages/"
        resp=self.session.post(url,json=body)
        # print(resp.text)
        return json.loads(resp.text)

    def delete_block(self,_id):
        url = "https://api.notion.com/v1/blocks/"+_id
        resp = self.session.delete(url)
        # print(resp.text)
        # data=json.loads(resp.text)
        if resp.status_code==200:
            return True
        return False


def hand_add(name,money, _type):
    result = notion.add_bill(name, money, _type)
    name = result["properties"]["名称"]["title"][0]["plain_text"]
    _type = result["properties"]["类型"]["select"]["name"]
    money = result["properties"]["金额"]["number"]
    return f"记录成功了！\n{name}|{_type}|{money}\n" + f'<a href="weixin://bizmsgmenu?msgmenuid=0&msgmenucontent=删除{result["id"]}">点击撤回</a>'
def count_borrow():
    borrow_info = {
    }

    start_cursor = None
    while True:
        query = {

            "filter": {
                "or": [
                    {
                        "property": "类型",
                        "select": {
                            "equals": "借贷"}
                    }, {
                        "property": "类型",
                        "select": {
                            "equals": "还款"}
                    }

                ]
            },

        }
        if start_cursor:
            query["start_cursor"] = start_cursor
        result = notion.query_database(notion.bill_database_id,query)
        bills = result["results"]
        for bill in bills:
            # print(bill)
            properties = bill["properties"]
            # print(properties)
            name=properties["名称"]["title"][0]["plain_text"]
            if  name not in borrow_info.keys():
                borrow_info[name]=0
            borrow_info[name] += properties["借贷汇总"]["formula"]["number"]
        if result["has_more"]:
            start_cursor = result["next_cursor"]
        else:
            break

    texts=""
    for k,v in borrow_info.items():
        if v:
            texts+=f"{k} : {v}\n"
    return  texts
def get_type(text):


    for key,value in types.items():
        for i in value:
            if i in text:
                return key
    return "日用"

def parse_bill(text):
    pass
    for  key in bill_keys:
        text_list = text.split(key)
        if len(text_list)>1:
            break
    if bill_keys.index(key)<2:
        #花了  赚了
        #sign 表示金额的正负
        sign=(bill_keys.index(key)-1) or 1
        money=float(text_list[-1])
        money*=sign
        _type = get_type(text_list[0])
        result = notion.add_bill(text_list[0],money,_type)
        name = result["properties"]["名称"]["title"][0]["plain_text"]
        _type = result["properties"]["类型"]["select"]["name"]
        money = result["properties"]["金额"]["number"]
        return f"记录成功了！\n{name}|{_type}|{money}\n" + f'<a href="weixin://bizmsgmenu?msgmenuid=0&msgmenucontent=删除{result["id"]}">点击撤回</a>'


    else:
        #借贷 和还钱的逻辑
        # print(text_list)陈小宝还款300   借给陈小宝300
        sign=-1 if key in ["借给","借了"] else 1

        number=re.findall('[0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*[eE][+-]?[0-9]+?$',text)

        money = float(number[0])
        money *= sign
        _type = get_type(key)
        name = text.replace(number[0],"")
        for i in bill_keys:
            name=name.replace(i,"")

        result = notion.add_bill(name, money, _type)

        name=result["properties"]["名称"]["title"][0]["plain_text"]
        _type=result["properties"]["类型"]["select"]["name"]
        money=result["properties"]["金额"]["number"]

        return f"记录成功了！\n{name}|{_type}|{money}\n" + f'<a href="weixin://bizmsgmenu?msgmenuid=0&msgmenucontent=删除{result["id"]}">点击撤回</a>'
def parse_day(text):

    is_learn="记了单词" in text
    result = notion.add_day_log(learn_en=is_learn)
    return "记录成功了！\n" + f'<a href="weixin://bizmsgmenu?msgmenuid=0&msgmenucontent=删除{result}">点击撤回</a>'
def delete(text):
    text=text.replace("删除","").strip()
    if notion.delete_block(text):
        return "删除成功！"
    return "删除失败"

def count(text):
    #先查询账单   在统计习惯
    if text=="今天汇总":
        start = datetime.date.today()
        end = start
    elif text=="本周汇总":
        end = datetime.date.today()
        start = datetime.date.today() - datetime.timedelta(end.weekday())
    elif text=="本月汇总":
        end= datetime.date.today()
        start = datetime.date(end.year, end.month, 1)
        # end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])
    elif text=="本年汇总":
        end= datetime.date.today()
        start = datetime.date(end.year, 1, 1)
    elif text=="昨天汇总":
        now = datetime.date.today()
        end =datetime.date.today() - datetime.timedelta(1)
        start=end
    elif text=="上周汇总":
        now = datetime.date.today()
        start = datetime.date.today() - datetime.timedelta(now.weekday()+7)
        end=start+datetime.timedelta(6)
    elif text=="上月汇总":
        now= datetime.date.today()
        if now.month==1:
            year=now.year-1
            month=12
        else:
            year=now.year
            month=now.month-1
        start = datetime.date(year, month, 1)
        end=datetime.date(now.year, now.month, 1)-datetime.timedelta(1)

    texts = notion.count(str(start),str(end))
    return text+"\n"+texts+"\n日期："+"-".join([str(start),str(end)])
def parse_text(text):

    if text=="菜单":
        _="点击查询\n"
        for k,v in meun.items():
            _ +=f'<a href="weixin://bizmsgmenu?msgmenuid=0&msgmenucontent={v}">{k}</a>\n'
        return _
    elif  text in model.keys():
        return model.get(text)
    elif text.startswith("删除"):
        return delete(text)
    elif text in count_keys:
        return count(text)
    #不是固定回复就 开始匹配
    elif text =="查询借贷":
        return count_borrow()
    for i in bill_keys:
        if i in text:
            return parse_bill(text)

    for i in days_keys:
        if i in text:
            return parse_day(text)
    return  "没有读懂哟"
notion = MyNotion()



